<template>
  <a-spin :spinning="loading" size="large">
    <van-form @submit="onSubmit" @failed="onFailed" ref="formRef">
      <h3>1.报修类型:</h3>
      <van-cell-group inset>
        <van-field v-model="dataList.bxTypeName" is-link readonly label="报修类型" placeholder="请选择" />
      </van-cell-group>
      <h3>2.报修科室:</h3>
      <van-cell-group inset>
        <van-field v-model="dataList.checkPlaceName" is-link readonly label="报修科室" placeholder="请选择"
          @click="type == 'info' ? mini = true : ''" />
      </van-cell-group>
      <h3>3.科室地点描述:</h3>
      <van-cell-group inset>
        <van-field v-model="dataList.checkPlace" type="textarea" rows="3" autosize placeholder="详情描述"
          :disabled="true"></van-field>
      </van-cell-group>
      <h3>4.报修详情描述:</h3>
      <van-cell-group inset>
        <van-field v-model="dataList.checkContent" type="textarea" rows="3" autosize placeholder="详情描述"
          :disabled="true"></van-field>
      </van-cell-group>
      <h3>5.报修照片:</h3>
      <van-cell-group inset>
        <a-image :width="150" v-for="item in JSON.parse(dataList.imgsAbnormalId)" :src="baseUrl + item"></a-image>
        <Empty image-size="100" v-if="!JSON.parse(dataList.imgsAbnormalId).length" description="暂无图片"></Empty>
      </van-cell-group>
      <br>
      <h3 class="red">*6.处理方法:</h3>
      <van-cell-group inset>
        <van-field v-model="dataList.handleMethod" type="textarea" rows="3" autosize :disabled="isUpdate"
          placeholder="请输入处理方法"></van-field>
      </van-cell-group>
      <h3 class="red">*7.处理结果:</h3>
      <van-cell-group inset>
        <van-field v-model="dataList.handleResult" type="textarea" rows="3" autosize :disabled="isUpdate"
          placeholder="请输入处理结果"></van-field>
      </van-cell-group>
      <h3 class="red">*8.事件状态:</h3>
      <van-radio-group v-model="dataList.eventType" :rules="[{required: true, message: '请选择事件状态'}]"
        :disabled="isUpdate">
        <van-cell-group inset>
          <van-cell title="未接单">
            <template #right-icon>
              <van-radio disabled name="0" />
            </template>
          </van-cell>
          <van-cell title="已接单" clickable @click="changeType(1)">
            <template #right-icon>
              <van-radio name="1" />
            </template>
          </van-cell>
          <van-cell title="处理中" clickable @click="changeType(2)">
            <template #right-icon>
              <van-radio name="2" />
            </template>
          </van-cell>
          <van-cell title="等待中" clickable @click="changeType(3)">
            <template #right-icon>
              <van-radio name="3" />
            </template>
          </van-cell>
          <van-cell title="已办结" clickable @click="changeType(4)">
            <template #right-icon>
              <van-radio name="4" />
            </template>
          </van-cell>
        </van-cell-group>
      </van-radio-group>
      <h3 class="red">*9.处理图片</h3>
      <van-cell-group inset>
        <van-uploader v-if="!isUpdate" v-model="fileListArr" :after-read="afterRead" :before-read="beforeRead"
          :preview-options='{closeable:true}'></van-uploader>
        <a-image v-else :width="150" v-for="item in JSON.parse(dataList.imgsHandleId)" :src="baseUrl + item"></a-image>
        <Empty v-if="isUpdate && (!dataList.imgsHandleId || !JSON.parse(dataList.imgsHandleId).length)" description="暂无图片"></Empty>
      </van-cell-group>
      <br>
      <van-cell-group inset>
        <van-steps direction="vertical" :active="active">
          <van-step v-for="item in flowList">
            <div class="role">{{ item.role_name }}</div>
            <div class="time">{{ item.record_time }}</div>
            <p class="title">{{ item.flow_name }}</p>
            <p class="method">{{ item.user_name || '未知人员' }}</p>
          </van-step>
        </van-steps>
      </van-cell-group>
      <br>
      <div class="btn">
        <van-button type="primary" @click="doSubmit" v-if="!isUpdate && type == 'notes'">{{ placeId == dataList.placeId ? '提交维修' :
          '流转处理'}}</van-button>
        <van-button type="success" @click="getForm" v-if="dataList.eventType == 0 && type == 'info'">{{ placeId == dataList.placeId ?
          '点击接单' : '流转处理'}}</van-button>
      </div>
    </van-form>

    <!-- 科室列表 -->
    <van-popup v-model:show="mini" position="bottom">
      <van-picker title="选择科室" :columns="gridList" @confirm="confirmGrid" @cancel="mini = false"
        :columns-field-names="{text:'placeName', value: 'id'}"></van-picker>
    </van-popup>

    <!-- 类型列表 -->
    <van-popup v-model:show="show" position="bottom">
      <van-picker title="选择类型" :columns="typeList" @confirm="confirmType" @cancel="show = false"
        :columns-field-names="{text:'typeName', value: 'id'}"></van-picker>
    </van-popup>
  </a-spin>
</template>

<script setup>
  import { ref, onMounted, inject } from "vue"
  import { Field as VanField, Form as VanForm, RadioGroup as VanRadioGroup, CellGroup as VanCellGroup, Uploader as VanUploader, Button as VanButton, Popup as VanPopup, Picker as VanPicker, Steps as VanSteps, Step as VanStep, Empty } from "vant";
  import { useRoute } from "vue-router";
  import router from "@/route/index.js";
  import { photoUploadBase64, getWxPlace, updateData, getWxType, getAbnormalDetail } from "@/api/common.js";
  import moment from "moment"
  import * as imageConversion from 'image-conversion'

  const mini = ref(false);
  const checkPlace = ref("");
  const checkType = ref("");
  const checkPlaceName = ref("");
  const checkTypeName = ref("");
  const loading = ref(false),
    show = ref(false),
    toast = inject("toast"),
    route = useRoute(),
    message = ref(""),
    messagePlace = ref(""),
    fileList = ref([]),
    fileListArr = ref([]),
    formRef = ref(null),
    recordId = ref(""),
    baseUrl = ref("http://101.68.222.195:9090/image/"),
    handleResult = ref(""),
    isUpdate = ref(true); //修改和详情
  const gridList = ref([]);
  const typeList = ref([]);
  const dataList = ref({
    imgsAbnormalId: '[]',
    imgsHandleId: '[]'
  });
  const flowList = ref([]);
  const active = ref(0);
  const placeId = ref("")
  const userInfo = ref(JSON.parse(localStorage.getItem("SAVE_USER_INFO")));
  const type = ref(null);

  onMounted(() => {
    type.value = route.query.type
    getWxPlace().then(res => {
      gridList.value = res
    })
    getWxType().then(res => {
      typeList.value = res
    })
    recordId.value = route.query.id
    getAbnormalDetail({ recordId: recordId.value }).then(res => {
      dataList.value = res.data
      dataList.value.eventType += ''
      placeId.value = dataList.value.placeId + ''

      // 1 已接单 2 处理中 3 等待中
      if ((dataList.value.eventType == 1 || dataList.value.eventType == 2 || dataList.value.eventType == 3) && type.value != 'detail' ) {
        // isUpdate为false则可修改
        isUpdate.value = false
      }
      if (dataList.value.imgsHandleId) {
        JSON.parse(dataList.value.imgsHandleId).forEach(item => {
          fileListArr.value.push({ url: baseUrl.value + item, msg: item })
        })
      }
      flowList.value = res.flowList
      active.value = flowList.value.length - 1
      if(type.value == 'notes') {
        dataList.value.eventType = '4'
      }
    })
  })

  function getForm() {
    let obj = JSON.parse(JSON.stringify(dataList.value))
    obj.eventType = 1
    obj.userId = userInfo.value.userId
    obj.userName = userInfo.value.realName
    obj.checkUserName = userInfo.value.realName
    updateData(obj).then(res => {
      if (res.code == 200) {
        toast.msg(res.message)
        router.go(-1)
      } else {
        toast.msg(res.message)
      }
    }, err => {
      toast.msg(err.message)
    })
  }

  function changeType(val) {
    if (!isUpdate.value) {
      dataList.value.eventType = val + ''
    }
  }

  function confirmGrid(val) {
    mini.value = false
    dataList.value.checkPlaceName = val.placeName
    dataList.value.placeId = val.id
  }

  function confirmType(val) {
    show.value = false
    checkTypeName.value = val.typeName
    checkType.value = val.id
  }

  function onFailed(error) {
    console.log(error)
  }

  function doSubmit() {
    formRef.value.submit();
  }

  function onSubmit() {
    if(dataList.value.eventType == 4 && (!dataList.value.handleMethod.trim() && !dataList.value.handleResult.trim())) {
      toast.error("办结工单请填写处理方法或处理结果！")
      return
    }
    if(dataList.value.eventType == 4 && !fileListArr.value.length) {
      toast.error("办结工单请上传处理图片！")
      return
    }
    let obj = {
      recordId: dataList.value.recordId,
      bxTypeId: dataList.value.bxTypeId,
      userId: userInfo.value.userId,
      checkUserName: userInfo.value.realName,
      userName: userInfo.value.realName,
      handleResult: dataList.value.handleResult.trim(),
      handleMethod: dataList.value.handleMethod.trim(),
      eventType: dataList.value.eventType,
      placeId: dataList.value.placeId,
      imgArrayHandle: fileListArr.value.map(item => item.msg)
    }
    loading.value = true
    updateData(obj).then(res => {
      if (res.code == 200) {
        toast.success('提交成功！');
        setTimeout(() => {
          loading.value = false;
          router.go(-1);
        }, 1000)
      } else {
        loading.value = false
        toast.msg(res.message)
      }
    }, err => {
      loading.value = false
      toast.msg(err)
    })
  }

  function beforeRead(file) {
    return new Promise((resolve, reject) => {
      imageConversion.compressAccurately(file, 200).then(res => {
        res = new File([res], file.name, { type: res.type, lastModified: Date.now() })
        resolve(res)
      })
    });
  }

  function afterRead(file) {
    uploadFile(file);
  }
  function uploadFile(file) {
    file.status = "uploading";
    loading.value = true;
    apiUpLoadImg(file);
  }

  function getBase64(file) {
    return new Promise(function (resolve, reject) {
      const reader = new FileReader();
      let imgResult = "";
      reader.readAsDataURL(file);
      reader.onload = function () {
        imgResult = reader.result;
      };
      reader.onerror = function (error) {
        reject(error);
      };
      reader.onloadend = function () {
        resolve(imgResult);
      };
    });
  }

  function apiUpLoadImg(file) {
    getBase64(file.file).then(res => {
      let obj = {
        base64: res
      }
      //接口需要传的参数
      photoUploadBase64(obj).then(res => {
        file.status = "success";
        file.msg = res.message;
        loading.value = false;
      }, err => {
        loading.value = false
        alert(err)
      })
    })
  }

</script>

<style lang="less" scoped>
  h3 {
    font-weight: 700;
    margin: 5px 15px;
  }

  h3.red {
    color: red;
  }

  .role {
    width: 40px;
    height: 40px;
    float: left;
    background-color: #5193f3;
    border-radius: 3px;
    color: #fff;
    font-size: 16px;
    line-height: 20px;
    text-align: center;
    font-weight: normal;
    font-family: adobe;
    margin-right: 8px;
  }

  .time {
    float: right;
    font-family: regular;
    color: #a0a0a0;
    font-size: 15px;
  }

  p {
    margin: 0;
    padding: 0;
    margin-left: 5px;
  }

  p.title {
    font-family: medium;
    color: #343434;
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 5px;
  }

  p.method {
    font-family: regular;
    color: #a0a0a0;
    font-size: 15px;
    font-weight: 400;
  }

  :deep(.van-field__label) {
    width: calc(100% - 150px);
  }

  .special :deep(.van-field__label) {
    width: calc(100% - 200px);
  }

  :deep(.van-uploader) {
    margin: 8px 0 0 10px;
  }

  .btn {
    margin: 0 16px;

    button {
      width: 100%;
      margin-bottom: 10px;
    }

  }

  :deep(.van-uploader__preview) {
    margin-right: 5px;
  }

  .home-title {

    margin-left: 15px;
    margin-top: 20px;

    h1 {
      font-weight: 700;
      margin: 0;
    }

    h3 {
      font-weight: 700;
      margin: 0;
      margin-left: 10px;
    }

    span {
      display: block;
      margin-left: 15px;
      margin-bottom: 3px;

      font.yellow {
        border: 1px solid greenyellow;
        color: greenyellow;
        padding: 1px 3px;
      }

      font.yellow {
        border: 1px solid #ffea00;
        color: #ffea00;
        padding: 1px 3px;
      }

      font.orange {
        border: 1px solid orange;
        color: orange;
        padding: 1px 3px;
      }

      font.red {
        border: 1px solid red;
        color: red;
        padding: 1px 3px;
      }

    }

  }

  :deep(.van-popup--bottom) {
    background-color: rgb(246, 247, 248);
  }
</style>